iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
自我挑戰組

C 語言筆記系列 第 16

[C 語言筆記--Day16] 紀錄前幾天寫錯的東西

  • 分享至 

  • xImage
  •  

前幾天寫了一個錯誤的寫法,

大致上的關係長的像是下面這樣

出錯的地方在於我在 .h 檔裏面定義了一個變數

為何不可以這樣寫、以及要如何在 .h 檔裏面定義變數

的細節其實也還不是很清楚,

但總之就先把錯誤的寫法紀錄下來

// hello.h

#ifndef HELLO_H
#define HELLO_H

char *str = "Hello World\n";
void say_hello();

#endif
// hello.c

#include <stdio.h>
#include "hello.h"

void say_hello()
{
    printf("%s", str);
}
// main.c
#include "hello.h"

int main(int argc, char **argv)
{
    say_hello();
    return 0;
}

編譯:

$ gcc -c main.c 
$ gcc -c hello.c 
$ gcc -o hello_world main.o hello.o 
/usr/bin/ld: hello.o:(.data.rel.local+0x0): multiple definition of `str'; main.o:(.data.rel.local+0x0): first defined here
collect2: error: ld returned 1 exit status

上一篇
[C 語言筆記--Day15] 如何清空終端機
下一篇
[C 語言筆記--Day17] 讓一個絕對不會 return 的 function 進行一點優化
系列文
C 語言筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言